<template>
    <div>
        <!-- <canvas id="canvas" width="800" height="600" ></canvas> -->
        <!-- <div id="three" ref="environment"></div> -->
        <div class="ls_maincont"></div>
        <!-- 头部 -->
        <div class="mainDiv shouye">
            <div class="m">
                <div class="stage_c_t">
                    <div class="c react">
                        <i class="l_up"></i>
                        <i class="l_down"></i>
                        <i class="r_up"></i>
                        <i class="r_down"></i>
                        <!-- 主界面头部 -->
                        <p v-for="item in dcsMainjizu">
                            <span style="font-size: 32px;color: white">{{ item }}</span>
                        </p>
                    </div>
                </div>
            </div>
            <div class="l">
                <div class="stage_c_r main_2">
                    <div class="t">
                        <div class="react">
                            <i class="l_up"></i>
                            <i class="l_down"></i>
                            <i class="r_up"></i>
                            <i class="r_down"></i>
                            <div class="title">
                                <img src="../assets/zjz.png" alt="" style="width: 30px; ">
                                <span
                                    style="font-size: 30px ;color: white;  height: 91px; line-height: 91px; ">异常报警</span>
                            </div>
                        </div>
                    </div>
                    <div class="d" id="envent_d">
                        <div class="envent_u">
                            <!--<span>时间</span><span>状态</span><span>描述</span>-->
                            <span style="color: white;">时间</span><span style="color: white;">描述</span>
                        </div>
                        <!-- 事件列表 -->
                        <div class="envent_d" id="indexEventList">
                            <p v-for="item in eventList" style="font-size: 15px">
                                <span style="font-size: 30px;color: white;">{{ item.t }}</span><span
                                    style="font-size: 30px;color: white;">{{ item.event }}</span>
                            </p>
                        </div>
                    </div>
                </div>

                <div class="stage_c_r main_1" style="margin-left: 10px">
                    <div class="t">
                        <div class="react">
                            <i class="l_up"></i>
                            <i class="l_down"></i>
                            <i class="r_up"></i>
                            <i class="r_down"></i>
                            <div class="title" style="display: flex; justify-content: space-between;">
                                <div style="width: 100%; height: 100%;">
                                    <div style="display: flex; justify-content: space-between;">

                                        <div style="display: flex; justify-content: space-around;">
                                            <div style="line-height: 91px;"><img src="../assets/zjz.png" alt=""
                                                    style="width: 30px; height: 30px; line-height: 91px;"></div>&emsp;
                                            <div style="font-size: 24px; height: 90px; line-height: 91px;">实时数据曲线</div>
                                        </div>
                                        <div style="display: flex; color: black;">
                                            <div style="width: 300px; text-align: center;">

                                                <el-select class="sdz-select" :teleported="false" filterable
                                                    collapse-tags-tooltip :max-collapse-tags="2"
                                                    v-model="searchData.sdzs" multiple collapse-tags clearable
                                                    placeholder="请选择特征值" style="width: 300px">
                                                    <el-option v-for="(item, index) in sdzOptions" :value="index"
                                                        :label="item.description" :key="index">
                                                        {{ item.description }}
                                                    </el-option>
                                                </el-select>
                                            </div>
                                            <div style="width: 100px; height: 40px; border: 1px solid   black;  text-align: center;  line-height: 40px; background-color: #5a9cf8; color: wheat; margin-left: 30px;"
                                                @click="searchHistoryData">查询</div>
                                        </div>

                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- 折现图  -->
                    <div id="history_echarts" class="echarts"></div>
                    <!-- 折现图 -->
                </div>
            </div>

            <div class="r">
                <div class="stage_c_r main_2" style="width: calc(100% - 8px)">
                    <div class="t">
                        <div class="react">
                            <i class="l_up"></i>
                            <i class="l_down"></i>
                            <i class="r_up"></i>
                            <i class="r_down"></i>
                            <div class="title">
                                <img src="../assets/zjz.png" alt="" style="width: 30px;">
                                <span style="font-size: 30px ;color: white;">燃烧数字化监测</span>
                            </div>
                        </div>
                    </div>
                    <div class="d main0">
                        <div class="envent_u">
                            <span>监测项</span>
                            <span>A1</span><span>A2</span><span>A3</span><span>A4</span>
                            <span>B1</span><span>B2</span><span>B3</span><span>B4</span>
                            <span>C1</span><span>C2</span><span>C3</span><span>C4</span>
                        </div>
                        <div class="envent_d" id="index_rsszhjk">
                                <!-- 温度 -->
                                <div class="envent_u">
                                    <span>温度(°C)</span>
                                    <span v-for="(item, index) in temperature"  :key="index">
                                        <div style="color: green;"   v-if="waining0wendu[index] === 0">{{ item }}</div>
                                        <div style="color: yellow;" v-if="waining0wendu[index] === 1">{{ item }}</div>
                                    <div style="color: red;" v-if="waining0wendu[index] === 2">{{ item }}</div>
                                    </span>
                                </div>
                                <!-- 着火距离 -->
                                <div class="envent_u">
                                    <span>着火距离(mm)</span>
                                    <span v-for="(item, index) in distance" :key="index">
                                        <div style="color: green;" v-if="waining0zhaohu[index] === 0">{{ item }}</div>
                                        <div style="color: yellow;" v-if="waining0zhaohu[index] === 1">{{ item }}</div>
                                    <div style="color: red;" v-if="waining0zhaohu[index] === 2">{{ item }}</div>
                                    </span>
                                </div>
                                <!-- 燃烧稳性 -->
                                <div class="envent_u">
                                    <span>燃烧稳定性(%)</span>
                                    <span v-for="(item, index) in stability" :key="index">
                                        <div style="color: green;" v-if="ranshaozhuandingxingwaining[index] === 0">{{ item }}</div>
                                        <div style="color: yellow;" v-if="ranshaozhuandingxingwaining[index] === 1">{{ item }}</div>
                                    <div style="color: red;" v-if="ranshaozhuandingxingwaining[index] === 2">{{ item }}</div>
                                    </span>
                                </div>
                        </div>
                        <!-- <div class="envent_u">
                            <span>监测项</span>
                            <span>D1</span><span>D2</span><span>D3</span><span>D4</span>
                            <span>E1</span><span>E2</span><span>E3</span><span>E4</span>
                            <span>S1</span><span>S2</span><span>S3</span><span>S4</span>
                        </div> -->
                        <!-- <div class="envent_d" id="index_rsszhjk"> -->
                                <!-- 温度 -->
                                <!-- <div class="envent_u">
                                    <span>温度(°C)</span>
                                    <span v-for="(item, index) in temperature"  :key="index">
                                        <div style="color: green;"   v-if="waining0wendu[index] === 0">{{ item }}</div>
                                        <div style="color: yellow;" v-if="waining0wendu[index] === 1">{{ item }}</div>
                                    <div style="color: red;" v-if="waining0wendu[index] === 2">{{ item }}</div>
                                    </span>
                                </div> -->
                                <!-- 着火距离 -->
                                <!-- <div class="envent_u">
                                    <span>着火距离(mm)</span>
                                    <span v-for="(item, index) in distance" :key="index">
                                        <div style="color: green;" v-if="waining0zhaohu[index] === 0">{{ item }}</div>
                                        <div style="color: yellow;" v-if="waining0zhaohu[index] === 1">{{ item }}</div>
                                    <div style="color: red;" v-if="waining0zhaohu[index] === 2">{{ item }}</div>
                                    </span>
                                </div> -->
                                <!-- 燃烧稳性 -->
                                <!-- <div class="envent_u">
                                    <span>燃烧稳定性(%)</span>
                                    <span v-for="(item, index) in stability" :key="index">
                                        <div style="color: green;" v-if="ranshaozhuandingxingwaining[index] === 0">{{ item }}</div>
                                        <div style="color: yellow;" v-if="ranshaozhuandingxingwaining[index] === 1">{{ item }}</div>
                                    <div style="color: red;" v-if="ranshaozhuandingxingwaining[index] === 2">{{ item }}</div>
                                    </span>
                                </div> -->
                        <!-- </div> -->
                    </div>
                </div>
            </div>
        </div>

        <div class="stage_t">
            <div class="stage_t_left">
                <img src="../assets/logins.jpg" alt=""> <span>国能怀安热电有限公司</span>
            </div>
            <div class="stage_t_zhong">燃烧数字化监测与可视化系统</div>
            <div class="stage_t_right">
                <img src="../assets/timer.png" alt=""> <span>{{ nowTime }}</span>
            </div>
        </div>
    </div>
    <div class="gongshi">
        <img src="../assets/zaiyi.jpg" alt="">
        <p>上海在伊环保科技有限公司</p>
    </div>
</template>

<script setup>



// 
import { ref, onMounted, reactive, watch, nextTick } from "vue";
import { formatTime } from "../utils/date.js";
import { postshouyewenduapi } from "../api/index.js";
import { getSDZlist2, history1, history } from "../api/canshushezhi.js";
import * as echarts from "echarts";
import { ElMessage } from 'element-plus'
import { ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
onMounted(async () => {
    setInterval(async () => {
        nowTime.value = formatTime(new Date());
    });

    //请求下面列表的
    obj();
    // 请求sdz接口
    await setSdzListData()

});
// 接口主界面逻辑的部分
// 机组实发功率
let dcsMainjizu = ref({});
// 事件列表
let eventList = ref({});
// 温度
let temperature = ref([])
// 温度 a-c
let temperatureAC = ref([])
let temperatureACs = ref([])
// 距离
let distance = ref([])
// 稳定性
let stability = ref([])
// 温度报警
let waining0wendu = ref([])
// 着火距离报警
let waining0zhaohu = ref([]);
// 燃烧稳性
let ranshaozhuandingxingwaining= ref([]);
// let timer = 0
let obj = async () => {
    // clearTimeout(timer)
    let res = await postshouyewenduapi();
    console.log(res);
    dcsMainjizu.value = res.data.dcsMain;
    eventList.value = res.data.events;
    temperature.value=[];
    distance.value=[];
    stability.value=[];
    //温度
    res.data.temperatures.map(item => {
        temperature.value.push(item)
    })
    res.data.distances.map(item => {
        distance.value.push(item)
    })
    res.data.stabilitys.map(item => {
        stability.value.push(item)
    })
     // 报警
    res.data.warnings0.map(item => {
        waining0wendu.value.push(item)
    })
    res.data.warnings1.map(item => {
        waining0zhaohu.value.push(item)
    })
    res.data.warnings2.map(item => {
        ranshaozhuandingxingwaining.value.push(item)
    })
    // timer = setTimeout(() => {
    //     obj();
    // }, 1000);
};


const nowTime = ref("");
const loading = ref(false);
const fullPage = ref(true);
// 获取当前日期
const today = new Date();
// 获取十天前的日期
const initStratTime = new Date(today);
initStratTime.setDate(today.getDate() - 10);

// 将十天前的日期设置为零时
initStratTime.setHours(0, 0, 0, 0);

// 获取今日的日期
const initEndTime = new Date(today);
// 将今日的日期设置为24时
initEndTime.setHours(23, 59, 59, 999);

const timeRange = ref([initStratTime, initEndTime])

const TIME_UNIT = [
    { value: 'd', label: '天' },
    { value: 'h', label: '时' },
    { value: 'm', label: '分' },
    { value: 's', label: '秒' },
]


let searchData = reactive({
    type: 0, //	默认定制查询0自定义查询1		
    valueStart: 400, //	定制追溯开始时间正整数		
    unitStart: "d", //	默认定制查询开始时间单位秒s分m时h天d，和自定义查询互斥（按钮置灰）		
    valueEnd: 0, //	定制追溯结束时间正整数		
    unitEnd: "d", //	默认定制查询结束时间单位秒s分m时h天d，和自定义查询互斥（按钮置灰）		
    value: 1, //	间隔数值正整数		
    unit: "d", //	查询间隔时间单位秒s分m时h天d		
    min: 0, //	过滤最小值		
    max: 2000, //	过滤最大值		
    sdzs: [],
});

const selectSDZArr = reactive([])

let myChart;
const serieData = reactive([])
const legendData = reactive([])
let timeoutCounter = -1

// watch(
//     () => searchData.sdzs.length,
//     (sdzs) => {
//         if (timeoutCounter !== -1) {
//             timeoutCounter = -1
//             clearTimeout(timeoutCounter)
//         }
//         timeoutCounter = setTimeout(function () {
//             timeoutCounter = -1
//             searchHistoryData()
//         }, 200)
//         // if (sdzs.length > 4) {
//         //     nextTick(() => {
//         //         ElMessage({
//         //             type: 'warning',
//         //             message: `SDZ最多只能选择4组数据`,
//         //         })
//         //     })
//         // }
//     }
// )


// 修改表格中的光标列
const changeValue = (arr) => {
    if (arr && arr.length > 0) {
        let selection = multipleTableRef.value.getSelectionRows()
        for (let i = 0; i < selection.length; i++) {
            if (arr[i] && arr[i].data) {
                selection[i].cursorVal = arr[i].data[1]
            } else {
                selection[i].cursorVal = ''
            }
        }
    }
}



const optionObj = {
    // 设置的是标题
    title: {
        text: '历史曲线'
    },
    tooltip: {
        trigger: 'axis',
        formatter: (c) => {
            let str = ''
            let temp = {
                showTime: '', // 时间
                marker: '', // 颜色
                seriesName: '', // legend名称
                valueData: '', // 数值
                setWidthSpan: '',
            }
            c.forEach((item) => {
                temp.showTime = item.data[0]
                temp.marker = item.marker
                temp.seriesName = item.seriesName
                temp.valueData = item.value[1]
                temp.setWidthSpan = '<span style="display:inline-block;width:10px;height:10px;"></span>'
                str += temp.marker + temp.seriesName + temp.setWidthSpan + temp.valueData + '<br />'
            })
            changeValue(c)
            return temp.showTime + '<br />' + str
        },
    },
    // 网格间距设置
    grid: {
        top: '40px',
        bottom: '50px',
        left: '60px',
        right: '60px',
        containLabel: true
    },
    dataZoom: [
        {
            type: 'slider',
            show: true,
            brushSelect: false,
            xAxisIndex: [0],
        },
        {
            type: 'slider',
            show: true,
            brushSelect: false,
            yAxisIndex: [0],
            left: '0%',
        },
        {
            type: 'inside',
            xAxisIndex: [0],
        },
        {
            type: 'inside',
            yAxisIndex: [0],
        }
    ],
    xAxis: {
        // xAxis的下不在设置data属性共享时间`
        type: 'time',
        splitLine: { show: true },
        lineStyle: {
            width: 2
        },
        axisTick: {
            show: false
        },
        axisLabel: {
            // 设置坐标轴上的时间格式
            formatter: function (value) {
                // console.log('时间戳', value)
                // 将时间转换为 JavaScript 日期对象  
                return backTime(value)
            },
            showMinLabel: true,
            showMaxLabel: true // 固定显示X轴的最后一条数据
        },
        // 更改x轴线的颜色
        axisLine: {
            lineStyle: {
                color: '#D2DBE6;',
                width: 1 // x轴线的宽度
            }
        },
    },
    yAxis: {
        type: 'value',
        splitLine: { show: true }
    }
}

onMounted(async () => {
    nowTime.value = formatTime(new Date());
    setInterval(() => {
        nowTime.value = formatTime(new Date());
    }, 1000);
    function $(el, all = false) {
        if (all) return document.querySelectorAll(el);
        return document.querySelector(el);
    }
    // 基于准备好的dom，初始化echarts实例
    myChart = echarts.init(document.getElementById("history_echarts"), 'dark');

    myChart.setOption(optionObj)

    myChart.on('tooltip', function (params) {
        // params 包含了当前鼠标所在的数据点信息
        var seriesData = params.data; // 获取当前鼠标所在的数据点
        console.log(seriesData);
    });

    // 请求接口的
    await setSdzListData()
    if (sdzOptions.length > 0) {
        // searchData.sdzs.push(0, 1, 2, 3)
        // searchHistoryData()
    }
    //  页面加载动画
    // doAjax()
});

const sdzOptions = reactive([])

// 设置SDZ数据
const setSdzListData = async () => {
    let sdzRes = await getSDZlist2();
    if (sdzRes.status !== 200) {
        return
    }
    sdzOptions.push(...sdzRes.data)
}

const resultTableData = reactive([])

function backTime(value) {
    let date = new Date(value);
    // 获取年份、月份和日期  
    let year = date.getFullYear();
    let month = date.getMonth() + 1; // 月份从 0 开始，需要加 1  
    let day = date.getDate();

    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();

    // 格式化月份和日期为两位数（不足两位时补零）  
    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day;

    hours = hours < 10 ? '0' + hours : hours;
    minutes = minutes < 10 ? '0' + minutes : minutes;
    seconds = seconds < 10 ? '0' + seconds : seconds;

    // 返回格式化后的字符串  
    return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
}

const multipleTableRef = ref(null)

let setInitSelected = true
// 历史曲线查询
const searchHistoryData = async (isDialog = false) => {
    timeoutCounter = -1
    clearTimeout(timeoutCounter)
    let params = JSON.parse(JSON.stringify(searchData));
    if (params.type === 1) {
        params.startTime = formatDate(timeRange.value[0])
        params.endTime = formatDate(timeRange.value[1])
    }
    if (isDialog === true) {
        params.sdzs = [...selectSDZArr]
    } else {
        if (!params.sdzs || params.sdzs.length < 1) {
            ElMessage({
                type: 'warning',
                message: `请选择特征值信息`,
            })
            return;
        } else if (params.sdzs.length > 4) {
            ElMessage({
                type: 'warning',
                message: `特征值最多只能选择4组数据`,
            })
            return;
        }
        else {
            const sdzsTemp = []
            params.sdzs.forEach(i => {
                sdzsTemp.push({
                    seq: sdzOptions[i].seq,
                    table0: sdzOptions[i].table0,
                    column0: sdzOptions[i].column0,
                    description: sdzOptions[i].description,
                })
            })
            params.sdzs = sdzsTemp
        }
    }
    loading.value = true
    let res = await history(params);
    loading.value = false
    if (res.status === 200) {
        myChart.clear();
        setInitSelected = true
        // const tempArr = selectSDZArr.slice(resultTableData.length)
        resultTableData.length = 0
        serieData.length = 0
        legendData.length = 0
        res.data.forEach((item, i) => {
            if (isDialog !== true) {
                selectSDZArr.length = 0
                searchData.sdzs?.forEach(i => {
                    selectSDZArr.push({ seq: searchData.sdzs[i], ...sdzOptions[i] })
                })
            }
            resultTableData.push(item)
            let description = item.description = item.description || `description_${selectSDZArr[i]?.seq}`
            legendData.push({ name: description })
            serieData.push({
                "name": description,
                "type": "line",
                "symbol": "none",
                "connectNulls": true,
                "showAllSymbol": true,
                // 让每一条折线拥有数据自己的时间
                "data": item.avgs.map(item => [item.t, item.avg]),
                "unit": "%",
                "markPoint": {
                    "symbol": "rect",
                    "symbolSize": "12",
                    "label": { "show": false },
                    "tooltip": { "triggerOn": "click", "trigger": "item" },
                }
            })
        });
        myChart.setOption(optionObj)
        myChart.setOption({
            series: serieData,
            legend: {
                data: legendData
            },
            yAxis: {
                max: (res.data[0] && res.data[0].max0) ? res.data[0].max0 : 4000,
                min: 0,
            }
        })
        nextTick(() => {
            multipleTableRef.value.toggleAllSelection()
            myChart.getOption()
        })
    }
};


const handleSelectionChange = (selection) => {
    const legendSelected = {}
    legendData.forEach((item, i) => {
        if (selection.find(
            row => {
                if (row.description) {
                    return row.description === item.name
                } else {
                    return row.seq == item.name.split('_')[1]
                }
            })
        ) {
            legendSelected[item.name] = true
        } else {
            legendSelected[item.name] = false
        }
    })
    myChart.setOption({ legend: { selected: legendSelected } })
}

const poperStyle = reactive({
    left: 0,
    top: 0,
    bottom: 'unset',
})
const popOverVisible = ref(false)
// 添加或删除 sdz
const currentClickNo = ref(-1)
const addOrDelete = (row, col, $event) => {
    $event.preventDefault();
    popOverVisible.value = true
    poperStyle.left = $event.pageX + 'px'
    // poperStyle.top = $event.pageY + 'px'
    // poperStyle.left = $event.clientX + 'px'
    poperStyle.top = ($event.y - 55) + 'px'
    currentClickNo.value = row.seq

    let clickHiddenEventFunc = function () {
        popOverVisible.value = false
        document.removeEventListener('click', clickHiddenEventFunc)
    }
    clickHiddenEventFunc = document.addEventListener('click', clickHiddenEventFunc)

}
const toAddSDZ = () => {
    dialogVisible.value = true

    nextTick(() => {
        if (setInitSelected) {
            dialogTableComp.value.toggleAllSelection()
            nextTick(() => {
                dialogTableComp.value.getSelectionRows().forEach(row => {
                    if (selectSDZArr.find(item => item.seq === row.seq)) {
                        dialogTableComp.value.toggleRowSelection(row, true)
                    } else {
                        dialogTableComp.value.toggleRowSelection(row, false)
                        console.log(row.seq)
                    }
                })
            })
            setInitSelected = false
        }
    })
}
const toDeleteSDZ = () => {
    if (currentClickNo.value > -1) {
        let deleteIndex = 0
        selectSDZArr.forEach((item, i) => {
            if (item.seq === currentClickNo.value) {
                deleteIndex = i
            }
        })
        selectSDZArr.splice(deleteIndex, 1)
        searchData.sdzs = searchData.sdzs.filter(i => sdzOptions[i].seq !== currentClickNo.value)
        currentClickNo.value = -1
        searchHistoryData(true)
    }
}

const changeMinMax = (row, col) => {
    if (col.type === 'selection') return
    myChart.setOption({
        yAxis: {
            max: Number(row.max),
            min: Number(row.min),
        }
    })
}
const filterValue = ref('')
const dialogVisible = ref(false)

watch(
    () => dialogVisible.value,
    (newVal) => {
        if (newVal) {
            dialogTableData.length = 0
            dialogTableData.push(...sdzOptions)
        }
    }
)

// 模糊查询点表
const dialogTableData = reactive([])
const toSearchSdz = () => {
    searchSdz(filterValue.value).then(res => {
        if (res.status === 200) {
            dialogTableData.length = 0
            dialogTableData.push(...res.data)
        }
    })
}

const dialogTableComp = ref(null)
// 弹窗确认按钮
const toConfirmDialog = () => {
    const rows = dialogTableComp.value.getSelectionRows()
    selectSDZArr.push(...rows)
    searchHistoryData(true)
    dialogVisible.value = false
}
</script>

<style scoped lang="scss">
.echarts {
    width: 100%;
    height: 400px;
    background: url(../assets/gx.png) no-repeat center;
}

// .sdz-select:deep(.el-select__selected-item .el-tag .is-closable .el-tag--info .el-tag--default .el-tag--light .el-tag__content .el-select__tags-text) {

//     color: black !important;
//     background-color: black;
// }
.gongshi {
    width: 100%;
    height: 60px;
    font-size: 20px;
    margin-top: 41px;
    text-align: center;
    color: white;
    background-color: #112b43;
    line-height: 60px;
    display: flex;
    justify-content: center;

    img {
        width: 30px;
        height: 30px;
        margin-top: 10px;
    }

}

.scrollbar-demo-item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
    margin: 10px;
    text-align: center;
    border-radius: 4px;
    background: var(--el-color-primary-light-9);
    color: var(--el-color-primary);
}
</style>